#ifndef __SWIIC_H_
#define __SWIIC_H_

#include "main.h"  //GPIO 初始化

#define OUTTIME 250     //ACK超时时间
#define IIC_Delay() 	HAL_Delay_us(4)     //设定电平保持时间，经过测量，在主频72M时3us IIC时钟速度为100K

#define __SDA_1 HAL_GPIO_WritePin(IIC->SDA.Port,IIC->SDA.Pin,GPIO_PIN_SET)    //SDA置高
#define __SDA_0 HAL_GPIO_WritePin(IIC->SDA.Port,IIC->SDA.Pin,GPIO_PIN_RESET)  //SDA置低

#define __SCL_1 HAL_GPIO_WritePin(IIC->SCL.Port,IIC->SCL.Pin,GPIO_PIN_SET)    //SCL置高
#define __SCL_0 HAL_GPIO_WritePin(IIC->SCL.Port,IIC->SCL.Pin,GPIO_PIN_RESET)  //SCL置低

#define	__SDA_READ HAL_GPIO_ReadPin(IIC->SDA.Port,IIC->SDA.Pin)    //读取SDA

#define SDA_IN()  IIC_GPIO_INPUT(IIC->SDA.Port,IIC->SDA.Pin); //更改SDA模式为输入
#define SDA_OUT() IIC_GPIO_OUTPUT(IIC->SDA.Port,IIC->SDA.Pin); //更改SDA模式为输出

#define 	IIC_MEMADD_SIZE_8BIT    			8       //寄存器地址为8位地址  
#define		IIC_MEMADD_SIZE_16BIT   			16      //寄存器地址为16位地址
extern enum __IIC_MEMADD_SIZE IIC_MEMADD_SIZE;          

typedef struct{
	uint32_t AHB;
	GPIO_TypeDef *Port;
	uint16_t Pin;
}IIC_GPIO;

typedef struct{
	IIC_GPIO SCL;
	IIC_GPIO SDA;
	uint8_t status;
	uint8_t addr;
}IIC_InitTypeDef;

extern IIC_GPIO ONE_SCL;
extern IIC_GPIO ONE_SDA;
extern IIC_InitTypeDef ONE_IIC;

void HAL_Delay_us(uint32_t nus);
void IIC_GPIO_INPUT(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin);
void IIC_GPIO_OUTPUT(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin);
    
void IIC_Start(IIC_InitTypeDef* IIC);
void IIC_Stop(IIC_InitTypeDef* IIC);
uint8_t IIC_WaitAck(IIC_InitTypeDef* IIC);
void IIC_Ack(IIC_InitTypeDef* IIC);
void IIC_NAck(IIC_InitTypeDef* IIC);
void IIC_SendByte(IIC_InitTypeDef* IIC,uint8_t _ucByte);
uint8_t IIC_ReadByte(IIC_InitTypeDef* IIC,uint8_t *read);

void IIC_Init(IIC_InitTypeDef* IIC);

uint8_t IIC_Read_Data(IIC_InitTypeDef* IIC,uint8_t *pData,uint16_t Len);
uint8_t IIC_Read(IIC_InitTypeDef* IIC,uint8_t *pData);
uint8_t IIC_Write(IIC_InitTypeDef* IIC,uint8_t *pData);
uint8_t IIC_Mem_Read(IIC_InitTypeDef* IIC,uint16_t MemAddr,uint8_t MemAddSize,uint8_t *pData,uint16_t Size);
uint8_t IIC_Mem_Write(IIC_InitTypeDef* IIC,uint16_t MemAddr,uint8_t MemAddSize,uint8_t *pData,uint16_t Size);

//示例复用IIC-Pin
#define    	IIC_SDA_AHB    RCC_IOPENR_GPIOBEN
#define    	IIC_SDA_Port   MT6701_B_GPIO_Port
#define    	IIC_SDA_Pin    MT6701_B_Pin
	
#define    	IIC_SCL_AHB    RCC_IOPENR_GPIOAEN
#define    	IIC_SCL_Port   MT6701_A_GPIO_Port
#define    	IIC_SCL_Pin    MT6701_A_Pin

void IIC_ONE_Init(void);
//示例复用IIC-Pin

#endif //__SWIIC_H_


